package edu.sdbi.judge.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import edu.sdbi.judge.domain.entity.Comment;
import edu.sdbi.judge.domain.entity.User;
import edu.sdbi.judge.domain.vo.StudentResult;
import edu.sdbi.judge.mapper.CommentMapper;
import edu.sdbi.judge.mapper.UserMapper;
import edu.sdbi.judge.service.GetJudgeIpResultService;
import edu.sdbi.judge.util.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 新增评论
 *
 * @author 孙阔
 */
@Order(8)
@Service
public class Judge8 implements GetJudgeIpResultService {

    @Autowired
    private HttpUtil httpUtil;
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public StudentResult getJudgeIpResult(String ip) {
        StudentResult studentResult = new StudentResult();
        JSONObject jsonResponse1 = null;
        JSONObject jsonResponse2 = null;
        double score = 0;
        //正常用户新增评论 (2分)
        String insertUrl = "http://" + ip + "/comment/insert";
        try {
            login("1", ip);
        } catch (Exception ignored) {
        }
        {   //String id="2";
            int commentType = 1;
            String relationId = "1";
            String text = "评论内容";
            JSONObject requestBody = new JSONObject();
            requestBody.put("type", Integer.toString(commentType));
            requestBody.put("relationId", relationId);
            requestBody.put("text", text);
            try {
                String resultStr = httpUtil.doPost(insertUrl, null, requestBody.toJSONString());

                jsonResponse1 = JSON.parseObject(resultStr);
                if (jsonResponse1 != null && jsonResponse1.getInteger("code") == 200) {
                    List<Comment> comment = commentMapper.selectByTextAndRelation(text, relationId);
                    if (comment != null && !comment.isEmpty()) {
                        score += 2;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //  已禁言用户新增评论
        //1.发送请求（内容避开数据库初始的数据）
        //判断：1.返回400 2.返回信息为："已被禁言，不能发布评论" 3.根据添加的信息查询数据库，如果为空加分
        {
            int commentType = 1;
            String relationId = "1";
            String text = "请求添加失败";
            JSONObject requestBody = new JSONObject();
            requestBody.put("type", Integer.toString(commentType));
            requestBody.put("relationId", relationId);
            requestBody.put("text", text);
            try {
                login("2", ip);
                String resultStr = httpUtil.doPost(insertUrl, null, requestBody.toJSONString());
                jsonResponse2 = JSON.parseObject(resultStr);
                if (jsonResponse2.getInteger("code") != 200) {
                    score += 2;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            login("1", ip);
        } catch (Exception ignored) {
        }
        if (jsonResponse1 != null && jsonResponse2 != null) {
            studentResult.setResult(jsonResponse1.toString() + jsonResponse2);
        }
        studentResult.setScore(score);
        studentResult.setItemNumber("8");
        return studentResult;
    }

    public void login(String userId, String ip) {
        //查询数据库中的用户信息
        User user = userMapper.getById(userId);
        String url = "http://" + ip + "/user/login?";
        //封装请求参数
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.add("username", user.getUsername());
        params.add("password", user.getPassword());
        try {
            //发送请求，获取返回值
            httpUtil.doPostFormData(url, null, params);
        } catch (Exception e) {
            //捕获异常情况，如404访问报错，返回值解析异常等，设置异常日志信息
            e.printStackTrace();
        }
    }
}